<template>
  <base-breadcrumb :title="titleName">
    <searchData :search-data="searchArr" @search="search" />

    <a-card :bordered="false">
      <!-- <title-name title="待读通知列表" /> -->

      <div class="table-operator">
        <a-button type="primary" :disabled="selectedRows.length == 0" :loading="readLoading" @click="readSelected">
          批量阅读
        </a-button>
      </div>

      <div class="pub-table-select-count">
        <a-icon type="info-circle" theme="twoTone" />
          <span style="margin-right: 12px">
           选中个数：<span class="totalNum">{{ selectedRowKeysRowLength || 0 }} 个</span>
        </span>
        <span style="margin-right: 12px">
          待读通知：<span class="totalNum">{{ totalSize || 0 }} 个</span>
        </span>
      </div>

      <list-table
        ref="table"
        row-key="id"
        :columns="columns"
        :request="loadData"
        :alert="true"
        :selectConfig = "{use: true, type: 'checkbox',rowKey: 'id' }"
        @select-click="selectClickFn"
      >
        <template slot="serial" slot-scope="text, record, index">
          <a-badge class="rowBadge" status="warning" :text="(index + 1).toString()" />
        </template>
        <template slot="status" slot-scope="text, record">
          <a-badge status="warning" :text="record.text && record.text.messageType === 4 ? '待处理' : '待读'" />
        </template>
        <template slot="type" slot-scope="text">
          <a-tag :color="text | typeColor">
            {{ text | newsTypeFilter }}
          </a-tag>
        </template>
        <template slot="name" slot-scope="text">
          <a-tooltip :title="text && text.length > 8 ? text : ''">
            {{ text }}
          </a-tooltip>
        </template>
        <template slot="content" slot-scope="text, record">
            {{text}}
            <span v-if="showJump(record)" style="color:#40a9ff;cursor: pointer;" @click="clickJump(record)">{{getJump(record)}}</span>
        </template>
        <template slot="action" slot-scope="text, record">
          <a v-if="record.text && record.text.messageType === 4" @click="handleSolve(record)">处理</a>
          <a v-else @click="handle(record)">查看</a>
        </template>
      </list-table>

      <!-- <a-table
        ref="table"
        :loading="loading"
        :pagination="false"
        :row-selection="rowSelection"
        :columns="columns"
        :data-source="tableData"
        row-key="id"
      >
        <template slot="serial" slot-scope="text, record, index">
          <a-badge class="rowBadge" status="warning" :text="(index + 1).toString()" />
        </template>
        <template slot="status" slot-scope="text, record">
          <a-badge status="warning" :text="record.text && record.text.messageType === 4 ? '待处理' : '待读'" />
        </template>
        <template slot="type" slot-scope="text">
          <a-tag :color="text | typeColor">
            {{ text | newsTypeFilter }}
          </a-tag>
        </template>
        <template slot="name" slot-scope="text">
          <a-tooltip :title="text && text.length > 8 ? text : ''">
            {{ text }}
          </a-tooltip>
        </template>
        <template slot="content" slot-scope="text, record">
          <a-tooltip
            :title="
              text && text.length > 64
                ? record.text && record.text.messageType === 4
                  ? resolveMessage(text).labelText
                  : text
                : ''
            "
          >
            {{ record.text && record.text.messageType === 4 ? resolveMessage(text).labelText : text }}
          </a-tooltip>
        </template>
        <template slot="action" slot-scope="text, record">
          <a v-if="record.text && record.text.messageType === 4" @click="handleSolve(record)">处理</a>
          <a v-else @click="handle(record)">查看</a>
        </template>
      </a-table> -->
      <!-- <pagination
        v-model="pageNo"
        :total="totalSize"
        :page-size.sync="pageSize"
        @change="handlePageChange"
        @showSizeChange="showSizeChange"
      /> -->
    </a-card>
    <!-- 处理弹窗 -->
    <a-modal v-model="visibleState.isResolve" title="处理">
      <span>{{ resolveInfo.labelText }}</span>
      <template slot="footer">
        <a-button type="default" :loading="loadingState.no" @click="confirmResolve('no')"> 否 </a-button>
        <a-button type="primary" :loading="loadingState.yes" @click="confirmResolve('yes')"> 是 </a-button>
      </template>
    </a-modal>
  </base-breadcrumb>
</template>

<script>
import moment from 'moment'
import messageBase from './baseconfig.js'
import { getTodoList, getTodoTotal } from '@/api/process'
import { messagePage, messageRead } from '@/api/messageSend'

import { getOrgEmployeeByUser } from '@/api/commons'

import { sloveArchiveMsg } from '@/api/office/archiveManage/archivePlan.js'

import Vue from 'vue'
import { message } from 'ant-design-vue'
import { packageConfirm } from '@/utils/baseAction.js'
import { jumpMixin } from "./jump";
export default {
  mixins:[jumpMixin], //混入文件
  name: 'ToReadList',
  components: {},
  data() {
    return {
      loadingState: {
        no: false,
        yes: false
      },
      resolveInfo: {}, // 存储需要处理的信息 id: 消息ID  keyText: 业务id   labelText: 业务消息内容
      visibleState: {
        isResolve: false
      },
      loading: false,
      readLoading: false,
      columns: messageBase.columns,
      searchArr: messageBase.searchArr,
      titleName: '',

      // 查询参数
      queryParam: {},
      selectedRowKeys: [],
      selectedRowKeysRowLength:0,
      selectedRows: [],
      tableData: [],
      totalSize: 1,
      pageNo: 0,
      pageSize: 10,
      currentUser: {},
      timer: null,
      timerLong: 30000,
      pathName: this.$route.path,

      loadData: (parameter) => {
        const query = this.queryParam
        query.hasRead = false
        const params = {
          ...parameter,
          needCount: true,
          query: query
        }
        return messagePage(params).then(res => {
          this.totalSize = res.totalSize;
            let count = isNaN(Number(res.totalSize)) ? 0 : Number(res.totalSize)
            this.$store.commit('messageInfo/SET_TOREADCOUNT', count)
            return res
        }) // 加载数据方法 必须为 Promise 对象
      }

    }
  },
  filters: {
    statusFilter(type) {
      return messageBase.statusMap[type] && messageBase.statusMap[type].text
    },
    statusTypeFilter(type) {
      return messageBase.statusMap[type] && messageBase.statusMap[type].status
    },
    newsTypeFilter(type) {
      return messageBase.newsTypeMap[type] && messageBase.newsTypeMap[type].text
    },
    typeColor(type) {
      return messageBase.newsTypeMap[type] && messageBase.newsTypeMap[type].color
    }
  },
  computed: {
    // rowSelection() {
    //   return {
    //     selectedRowKeys: this.selectedRowKeys,
    //     selectedRows: this.selectedRows, // 当前行所有数据
    //     onChange: this.onSelectChange
    //   }
    // },
    details() {
      const text = this.$route.query.detail
        ? JSON.parse(this.$route.query.detail)
        : {
          title: '',
          createTime: '',
          content: '',
          messageType: ''
        }
      if (text.messageType && messageBase.newsTypeMap[text.messageType]) {
        text.messageType = messageBase.newsTypeMap[text.messageType].text
      }
      return text
    }
  },
  created() {
    this.currentUser = Vue.getAcloudProvider().getUserInfo()
    this.destoryTimer()
    // this.getMessagePage()
    // this.$refs.table.refresh(true)
  },
  mounted() {
    console.log('mounted-----------table的Path', this.pathName)
    // 监听详情页返回刷新列表
    //this.pathName取的值是this.$route.path
    this.$bus.$on('handleRefresh' + this.pathName, () => {
      console.log('--------------------收到了，刷新刷新刷新----------------', this.pathName)
      // this.getMessagePage()
      this.$refs.table.refresh(true)
    })
  },
  beforeDestroy() {
    this.destoryTimer()
    console.log('beforeDestroy-------table的Path', this.pathName)
    this.$bus.$off('handleRefresh' + this.pathName)
  },
  methods: {
    resolveMessage(msg) {
      if (!msg)
        return {
          originText: msg,
          keyText: '',
          labelText: msg
        }
      let key = ''
      ;(msg.replace &&
        msg.replace(/^\[(.+?)\]/g, function(...args) {
          key = args[0]
        })) ||
      ''
      return {
        originText: msg,
        keyText: key.substring(1, key.length - 1),
        labelText: (msg.replace && msg.replace(key, '')) || ''
      }
    },
    /**
     * 确认处理
     * @param {String} type 'yes' | 'no' 分别对应用户操作： 是  |  否
     */
    async confirmResolve(type) {
      try {
        if (this.loadingState[type]) return
        this.loadingState[type] = true
        const params = {
          id: this.resolveInfo.keyText,
          ifOnTimeArchive: type === 'yes'
        }
        await sloveArchiveMsg(params)
        await messageRead({ ids: [this.resolveInfo.id] }) // 处理之后将消息置为已读
        this.$message.success('处理成功')
        // this.getMessagePage()
        this.$refs.table.refresh(true)
      } catch (e) {
        console.error(e)
      }
      this.visibleState.isResolve = false // 关闭弹窗
      this.loadingState[type] = false
    },
    /**
     * 处理事项
     */
    handleSolve(data) {
      const { keyText, labelText } = this.resolveMessage(data.text.content)
      this.resolveInfo = {
        id: data.id,
        keyText,
        labelText
      }
      this.visibleState.isResolve = true
    },
    getMessagePage() {
      this.loading = true
      const query = this.queryParam
      query.hasRead = false
      const params = {
        needCount: true,
        pageNo: this.pageNo,
        pageSize: this.pageSize,
        query: query
      }
      messagePage(params)
        .then(res => {
          this.loading = false
          if (res.code == '200') {
            this.tableData = res.data
            this.totalSize = res.totalSize
            let count = isNaN(Number(this.totalSize)) ? 0 : Number(this.totalSize)
            this.$store.commit('messageInfo/SET_TOREADCOUNT', count)
            this.destoryTimer()
            this.timer = setTimeout(() => {
              this.getMessagePage()
            }, this.timerLong)
          } else {
            let message = res.message || '请求失败'
            this.$message.error(res.message)
          }
        })
        .catch(err => {
          this.loading = false
        })
    },
    readSelected() {
      if (this.selectedRows.length == 0) return
      const params = {
        ids: this.selectedRowKeys
      }
      messageRead(params).then(res => {
        if (res && res.data && res.data.code == '200') {
          this.$message.success('查看成功！')
          this.selectedRowKeysRowLength = 0;
          this.selectedRowKeys = []
          this.selectedRows = []
          // this.getMessagePage()
          this.$refs.table.refresh(true)
        } else {
          this.$message.error(res.data.message ? res.data.message : '查看失败！')
        }
      })
    },
    // 清除定时器
    destoryTimer() {
      if (this.timer) {
        clearTimeout(this.timer)
        this.timer = null
      }
    },
    handlePageChange(pageNo) {
      this.pageNo = pageNo
      this.getMessagePage()
    },
    showSizeChange(pageNo, pageSize) {
      this.pageNo = 1
      this.pageSize = pageSize
      this.getMessagePage()
    },
    search(val) {
      if (val.createTime && val.createTime.length > 0) {
        this.queryParam.startTime = val.createTime[0].format('YYYY-MM-DD') + ' 00:00:00'
        this.queryParam.endTime = val.createTime[1].format('YYYY-MM-DD') + ' 23:59:59'
      } else {
        this.queryParam.startTime = ''
        this.queryParam.endTime = ''
      }
      this.queryParam.contentLike = val.contentLike || ''
      this.queryParam.messageType = val.messageType || ''
      this.queryParam.title = val.title || ''
      // this.getMessagePage()
      this.$refs.table.refresh(true)
    },
    handle(val) {
      const params = val.text ? val.text : {}
      params.createTime = val.createTime ? val.createTime : ''
      params.id = val.id
      //抄送通知
      if (val.text.messageType == 6) {
        let data = JSON.parse(val.text.extend)
        let routeData = this.$router.resolve({
          path: data.pcUrl,
          query: {
            procInstId: data.procInstId,
            businessId: data.businessId,
            typess: 'read',
            detailId: val.id //数据id详情页调用查看成功接口
          }
        })
        window.open(routeData.href, '_blank')
      } else {
        this.$router.push({
          path: '/matters/news/toread/detail',
          query: {
            detail: JSON.stringify(params)
          }
        })
      }
    },
    selectClickFn(selectData) {
      console.log(selectData, 'rows');
      this.selectedRowKeys = selectData.keys
      this.selectedRowKeysRowLength = selectData.rows.length
      this.selectedRows = selectData.rows
    },
    // onSelectChange(selectedRowKeys, selectedRows) {
    //   this.selectedRowKeys = selectedRowKeys
    //   this.selectedRows = selectedRows
    // }
  },
  watch: {
    selectedRows(newVal) {
      console.log(newVal, 'newVal');
      this.selectedRows = newVal;
    }
  }
}
</script>
<style>
.rowBadge .ant-badge-status-dot {
  width: 10px;
  height: 10px;
  top: -2px;
}
</style>
